package com.zjsru.plan2024.oneday;

/**
 * 2288. 价格减免
 *
 * @Author: cookLee
 * @Date: 2024-06-18
 */
public class DiscountPrices {

    /**
     * 主
     * \
     * 输入：sentence = "there are $1 $2 and 5$ candies in the shop", discount = 50
     * 输出："there are $0.50 $1.00 and 5$ candies in the shop"
     * 解释：
     * 表示价格的单词是 "$1" 和 "$2" 。
     * - "$1" 减免 50% 为 "$0.50" ，所以 "$1" 替换为 "$0.50" 。
     * - "$2" 减免 50% 为 "$1" ，所以 "$1" 替换为 "$1.00"
     * \
     * 输入：sentence = "1 2 $3 4 $5 $6 7 8$ $9 $10$", discount = 100
     * 输出："1 2 $0.00 4 $0.00 $0.00 7 8$ $0.00 $10$"
     * 解释：
     * 任何价格减免 100% 都会得到 0 。
     * 表示价格的单词分别是 "$3"、"$5"、"$6" 和 "$9"。
     * 每个单词都替换为 "$0.00"。
     * \
     *
     * @param args args
     */
    public static void main(String[] args) {
        DiscountPrices discountPrices = new DiscountPrices();
        String sentence = "$76111 ab $6 $";
        int discount = 48;
        System.out.println(discountPrices.discountPrices(sentence, discount));
    }

    /**
     * 美元符号
     */
    private final Character CHAR_DOLLAR = '$';

    /**
     * 字符串格式
     */
    private final String string_format = "$%.2f";

    /**
     * 模拟
     *
     * @param sentence 句子
     * @param discount 折扣
     * @return {@link String}
     */
    public String discountPrices(String sentence, int discount) {
        String[] split = sentence.split(" ");
        for (int i = 0; i < split.length; i++) {
            String s = split[i];
            //判断是不是$开头
            if (s.charAt(0) == CHAR_DOLLAR && this.helper(s.substring(1))) {
                //按照折扣进行替换
                double priece = Long.parseLong(s.substring(1)) * (1 - discount / 100.0);
                split[i] = String.format(string_format, priece);
            }
        }
        //拼接原数组
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < split.length; i++) {
            if (i > 0) {
                sb.append(" ");
            }
            sb.append(split[i]);
        }
        return sb.toString();
    }

    /**
     * 计算是不是字符串是不是只有数字组成
     *
     * @param substring 子字符串
     * @return boolean
     */
    private boolean helper(String substring) {
        if (substring.isEmpty()) {
            return false;
        }
        for (int i = 0; i < substring.length(); i++) {
            if (!Character.isDigit(substring.charAt(i))) {
                return false;
            }
        }
        return true;
    }
}
